package com.yihu.cms.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.yihu.beans.ResultVO;
import com.yihu.beans.user.UserPriviledge;
import com.yihu.cms.service.UserService;
import com.yihu.cms.util.CMSConstants;
import com.yihu.cms.util.InfoHelp;
import com.yihu.cms.util.PropertiesUtil;

public class SpringMVCInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("afterCompletion");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("postHandle");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub 
		// false end.  true continue
		String path = request.getServletPath();
		System.out.println("preHandle: "+path);
		String isInterceptor = PropertiesUtil.getInstance().getProperty("isInterceptor");
		if("0".equals(isInterceptor)){
			String strId = request.getParameter("userId");
			long id=0;
			if(strId!=null&!InfoHelp.isBlank(strId)){
				id= Long.parseLong(strId);
			}else{
				return true;
			}
			UserService as = new UserService();
			Object o = as.getPriviledgesByUserId(id);
			if(o instanceof ResultVO){
				response.getWriter().write(JSON.toJSONString(o));
			}
			else{
				List<UserPriviledge> ps = (List)o;
				for(UserPriviledge up:ps){
					if(up.getResourceURI().equals(path)){
						return true;
					}
				}
				ResultVO r = new ResultVO();
				r.setResult(CMSConstants.RESULT_CODE_FAIL);
				r.setMessage("No permissions");
				response.getWriter().write(JSON.toJSONString(r));
			}
			return false;
		}
		else 
			return true;

	}

}
